package com.example.managemyself.ui.diary;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.util.DateManager;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.util.MediaFileManager;
import com.example.managemyself.viewmodel.DiaryViewModel;
import com.example.managemyself.viewmodel.TaskViewModel;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 日记功能Fragment - 直接编辑模式
 * 显示当天日记内容，支持直接编辑和保存
 * 支持多媒体文件导入和任务完成自动记录
 */
public class DiaryFragment extends Fragment implements DateManager.DateChangeListener {
    
    private static final String TAG = "DiaryFragment";
    private static final int REQUEST_IMAGE_CAPTURE = 1001;
    private static final int REQUEST_IMAGE_PICK = 1002;
    private static final int REQUEST_VIDEO_CAPTURE = 1003;
    private static final int REQUEST_VIDEO_PICK = 1004;
    private static final int REQUEST_AUDIO_PICK = 1005;
    private static final int REQUEST_DOCUMENT_PICK = 1006;
    
    // 权限请求码
    private static final int PERMISSION_REQUEST_CAMERA = 2001;
    private static final int PERMISSION_REQUEST_STORAGE = 2002;
    
    // UI组件
    private TextView tvDate;
    private TextView tvWeather;
    private EditText etTitle;
    private EditText etContent;
    private TextView tvWordCount;
    private View layoutContent;
    private LinearLayout layoutAttachments;
    private RecyclerView recyclerViewCompletedTasks;
    
    // 数据和状态
    private DiaryViewModel diaryViewModel;
    private TaskViewModel taskViewModel;
    private DiaryEntry currentDiary;
    private boolean isEditMode = false;
    private SimpleDateFormat dateFormat;
    private DateManager dateManager;
    private Date currentDate;
    private MediaFileManager mediaFileManager;
    
    // 菜单项
    private MenuItem editMenuItem;
    private MenuItem saveMenuItem;
    private MenuItem attachMenuItem;
    
    // 附件列表
    private List<String> attachmentPaths = new ArrayList<>();
    private List<String> attachmentTypes = new ArrayList<>();
    private CompletedTasksAdapter completedTasksAdapter;
    
    // 临时文件路径（用于相机拍照/录像）
    private String currentPhotoPath;
    private String currentVideoPath;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mediaFileManager = new MediaFileManager(requireContext());
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_diary_enhanced, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);
        initViewModel();
        setupDateManager();  // 先设置日期管理器，确保currentDate被初始化
        initDateFormat();    // 然后初始化日期格式和显示
        loadCurrentDiary();
        setupEditTextListeners();
        setupCompletedTasksRecyclerView();
        loadCompletedTasks();
    }
    
    private void initViews(View view) {
        tvDate = view.findViewById(R.id.tv_date);
        tvWeather = view.findViewById(R.id.tv_weather);
        etTitle = view.findViewById(R.id.et_title);
        etContent = view.findViewById(R.id.et_content);
        tvWordCount = view.findViewById(R.id.tv_word_count);
        layoutContent = view.findViewById(R.id.layout_content);
        layoutAttachments = view.findViewById(R.id.layout_attachments);
        recyclerViewCompletedTasks = view.findViewById(R.id.recycler_completed_tasks);
    }
    
    private void initViewModel() {
        diaryViewModel = new ViewModelProvider(this).get(DiaryViewModel.class);
        taskViewModel = new ViewModelProvider(requireActivity()).get(TaskViewModel.class);
    }
    
    private void setupDateManager() {
        dateManager = DateManager.getInstance();
        if (dateManager != null) {
        dateManager.addDateChangeListener(this);
            currentDate = dateManager.getSelectedDate();
        }
        if (currentDate == null) {
            currentDate = new Date();
        }
    }
    
    private void initDateFormat() {
        dateFormat = new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.getDefault());
        updateDateDisplay();
    }
    
    private void updateDateDisplay() {
        if (currentDate == null) {
            Log.w(TAG, "currentDate为空，使用当前日期");
            currentDate = new Date();
        }
        
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.getDefault());
        }
        
        String dateStr = dateFormat.format(currentDate);
        if (tvDate != null) {
            tvDate.setText(dateStr);
        }
        
        // 设置天气信息（可以从天气服务获取）
        if (tvWeather != null) {
            tvWeather.setText("晴朗");
        }
    }
    
    private void loadCurrentDiary() {
        if (currentDate != null) {
            Log.d(TAG, "loadCurrentDiary: 加载日期=" + new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(currentDate));
            
            diaryViewModel.getDiaryEntryByDate(currentDate).observe(getViewLifecycleOwner(), diary -> {
                Log.d(TAG, "loadCurrentDiary: 收到数据库回调，diary=" + (diary != null ? "存在" : "null"));
                
                if (diary != null) {
                    Log.d(TAG, "loadCurrentDiary: 日记详情 - ID=" + diary.getId() + 
                               ", 标题=" + diary.getTitle() + 
                               ", 内容长度=" + (diary.getContent() != null ? diary.getContent().length() : 0));
                    
                    // 检查附件数据
                    List<String> paths = diary.getAttachmentPaths();
                    List<String> types = diary.getAttachmentTypes();
                    Log.d(TAG, "loadCurrentDiary: 附件数据 - paths=" + (paths != null ? paths.size() + "个" : "null") + 
                               ", types=" + (types != null ? types.size() + "个" : "null"));
                    
                    if (paths != null && !paths.isEmpty()) {
                        for (int i = 0; i < paths.size(); i++) {
                            Log.d(TAG, "loadCurrentDiary: 附件[" + i + "] = " + paths.get(i));
                        }
                    }
                    
                    // 检查完成任务数据
                    List<String> taskIds = diary.getCompletedTaskIds();
                    String taskSummary = diary.getCompletedTasksSummary();
                    Log.d(TAG, "loadCurrentDiary: 完成任务数据 - taskIds=" + (taskIds != null ? taskIds.size() + "个" : "null") + 
                               ", summary=" + (taskSummary != null ? taskSummary.length() + "字符" : "null"));
                }
                
                currentDiary = diary;
                updateUI();
            });
        } else {
            Log.w(TAG, "loadCurrentDiary: currentDate为空");
        }
    }
    
    private void setupEditTextListeners() {
        // 标题变化监听
        etTitle.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus && isEditMode) {
                updateWordCount();
            }
        });
        
        // 内容变化监听
        etContent.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus && isEditMode) {
                updateWordCount();
            }
        });
    }
    
    private void setupCompletedTasksRecyclerView() {
        completedTasksAdapter = new CompletedTasksAdapter();
        recyclerViewCompletedTasks.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewCompletedTasks.setAdapter(completedTasksAdapter);
    }
    
    private void loadCompletedTasks() {
        if (taskViewModel == null || currentDate == null) {
            Log.w(TAG, "TaskViewModel或currentDate为空，无法加载完成任务");
            return;
        }
        
        Log.d(TAG, "开始加载完成任务，日期: " + new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(currentDate));
        
        // 使用同步方法获取完成的任务
        new Thread(() -> {
            try {
                List<Task> completedTasks = taskViewModel.getCompletedTasksByDateSync(currentDate);
                
                // 在主线程更新UI
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Log.d(TAG, "获取到完成任务数量: " + (completedTasks != null ? completedTasks.size() : 0));
                        
                        if (completedTasks != null && !completedTasks.isEmpty()) {
                            completedTasksAdapter.setTasks(completedTasks);
                            recyclerViewCompletedTasks.setVisibility(View.VISIBLE);
                            
                            // 自动添加完成的任务到日记内容
                            addCompletedTasksToDiary(completedTasks);
                        } else {
                            // 没有完成任务时，显示提示信息
                            completedTasksAdapter.setTasks(new ArrayList<>());
                            recyclerViewCompletedTasks.setVisibility(View.GONE);
                            Log.d(TAG, "没有找到完成的任务");
                            
                            // 测试：创建一个虚拟的完成任务来验证显示
                            if (getContext() != null) {
                                Log.d(TAG, "创建测试完成任务");
                                List<Task> testTasks = new ArrayList<>();
                                Task testTask = new Task("测试完成任务", "这是一个测试任务");
                                testTask.setId(999);
                                testTask.setType("测试");
                                testTask.setCompletedDate(new Date());
                                testTask.setCompleted(true);
                                testTasks.add(testTask);
                                
                                completedTasksAdapter.setTasks(testTasks);
                                recyclerViewCompletedTasks.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "加载完成任务失败", e);
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        recyclerViewCompletedTasks.setVisibility(View.GONE);
                    });
                }
            }
        }).start();
    }
    
    private void addCompletedTasksToDiary(List<Task> completedTasks) {
        if (completedTasks == null || completedTasks.isEmpty()) {
            Log.d(TAG, "没有完成的任务需要添加到日记");
            return;
        }
        
        Log.d(TAG, "开始添加完成任务到日记，任务数量: " + completedTasks.size());
        
        StringBuilder taskSummary = new StringBuilder();
        taskSummary.append("\n\n📋 今日完成任务：\n");
        
        for (Task task : completedTasks) {
            taskSummary.append("✅ ").append(task.getTitle());
            if (task.getDescription() != null && !task.getDescription().isEmpty()) {
                taskSummary.append(" - ").append(task.getDescription());
            }
            
            // 添加完成时间
            if (task.getCompletedDate() != null) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
                taskSummary.append(" (").append(timeFormat.format(task.getCompletedDate())).append(")");
            }
            
            taskSummary.append("\n");
        }
        
        // 检查当前内容是否已包含任务摘要
        String currentContent = etContent.getText().toString();
        if (!currentContent.contains("📋 今日完成任务：")) {
            etContent.append(taskSummary.toString());
            updateWordCount();
            
            // 保存到数据库
            if (currentDiary != null) {
                // 更新日记的完成任务摘要
                currentDiary.updateCompletedTasksSummary(taskSummary.toString());
                for (Task task : completedTasks) {
                    currentDiary.addCompletedTask(String.valueOf(task.getId()));
                }
                
                // 立即保存到数据库
                new Thread(() -> {
                    try {
                        diaryViewModel.updateDiaryEntry(currentDiary);
                        Log.d(TAG, "完成任务摘要已保存到日记");
                    } catch (Exception e) {
                        Log.e(TAG, "保存完成任务摘要失败", e);
                    }
                }).start();
            }
            
            Log.d(TAG, "完成任务已添加到日记内容");
        } else {
            Log.d(TAG, "日记内容已包含完成任务摘要，跳过添加");
        }
    }
    
    private void updateUI() {
        Log.d(TAG, "updateUI: 开始更新UI，currentDiary=" + (currentDiary != null ? "存在(ID=" + currentDiary.getId() + ")" : "null"));
        
        if (currentDiary != null) {
            // 显示现有日记内容
            etTitle.setText(currentDiary.getTitle());
            etContent.setText(currentDiary.getContent());
            
            Log.d(TAG, "updateUI: 日记标题=" + currentDiary.getTitle());
            Log.d(TAG, "updateUI: 日记内容长度=" + (currentDiary.getContent() != null ? currentDiary.getContent().length() : 0));
            
            // 加载附件
            loadAttachments(currentDiary);
            updateWordCount();
            
            // 测试：如果没有附件数据，创建一些测试数据
            if ((currentDiary.getAttachmentPaths() == null || currentDiary.getAttachmentPaths().isEmpty()) && 
                layoutAttachments.getChildCount() == 0) {
                Log.d(TAG, "updateUI: 没有附件数据，显示测试提示");
                TextView testView = new TextView(getContext());
                testView.setText("📎 暂无附件（测试提示）");
                testView.setPadding(16, 16, 16, 16);
                testView.setTextSize(14);
                layoutAttachments.addView(testView);
            }
        } else {
            Log.d(TAG, "updateUI: 创建新日记");
            // 新建日记
            etTitle.setText("");
            etContent.setText("");
            clearAttachments();
            updateWordCount();
            
            // 为新日记显示提示
            TextView testView = new TextView(getContext());
            testView.setText("📝 这是新的日记，可以添加附件和记录完成的任务");
            testView.setPadding(16, 16, 16, 16);
            testView.setTextSize(14);
            layoutAttachments.addView(testView);
        }
        
        // 根据编辑模式设置UI状态
        updateEditMode();
        Log.d(TAG, "updateUI: UI更新完成");
    }
    
    private void loadAttachments(DiaryEntry diary) {
        if (diary == null) {
            Log.d(TAG, "loadAttachments: diary为空");
            return;
        }
        
        Log.d(TAG, "loadAttachments: 开始加载附件，diary ID=" + diary.getId());
        
        // 清除现有附件显示
        layoutAttachments.removeAllViews();
        attachmentPaths.clear();
        attachmentTypes.clear();
        
        // 加载保存的附件
        List<String> paths = diary.getAttachmentPaths();
        List<String> types = diary.getAttachmentTypes();
        
        Log.d(TAG, "loadAttachments: paths=" + (paths != null ? paths.size() : "null") + 
                   ", types=" + (types != null ? types.size() : "null"));
        
        if (paths != null && types != null && paths.size() == types.size()) {
            Log.d(TAG, "loadAttachments: 找到" + paths.size() + "个附件");
            for (int i = 0; i < paths.size(); i++) {
                String path = paths.get(i);
                String type = types.get(i);
                
                Log.d(TAG, "loadAttachments: 加载附件[" + i + "] path=" + path + ", type=" + type);
                
                attachmentPaths.add(path);
                attachmentTypes.add(type);
                
                // 根据类型创建对应的附件视图
                View attachmentView = createAttachmentViewFromSavedFixed(path, type);
                if (attachmentView != null) {
                    layoutAttachments.addView(attachmentView);
                    Log.d(TAG, "loadAttachments: 附件视图[" + i + "]创建成功");
                } else {
                    Log.w(TAG, "loadAttachments: 附件视图[" + i + "]创建失败");
                }
            }
        } else {
            Log.d(TAG, "loadAttachments: 没有找到有效的附件数据");
        }
        
        // 兼容旧的imageUri字段
        if (diary.getImageUri() != null && !diary.getImageUri().isEmpty()) {
            String imagePath = diary.getImageUri();
            Log.d(TAG, "loadAttachments: 找到旧格式图片 " + imagePath);
            if (!attachmentPaths.contains(imagePath)) {
                attachmentPaths.add(imagePath);
                attachmentTypes.add("image");
                View imageView = createAttachmentViewFromSavedFixed(imagePath, "image");
                if (imageView != null) {
                    layoutAttachments.addView(imageView);
                    Log.d(TAG, "loadAttachments: 旧格式图片视图创建成功");
                }
            }
        }
        
        Log.d(TAG, "loadAttachments: 完成，共显示" + layoutAttachments.getChildCount() + "个附件");
    }
    
    /**
     * 加载视频缩略图
     */
    private void loadVideoThumbnail(ImageView imageView, String videoPath) {
        try {
            File videoFile = new File(videoPath);
            if (videoFile.exists()) {
                // 使用MediaMetadataRetriever获取视频缩略图
                android.media.MediaMetadataRetriever retriever = new android.media.MediaMetadataRetriever();
                try {
                    retriever.setDataSource(videoPath);
                    android.graphics.Bitmap bitmap = retriever.getFrameAtTime(1000000); // 获取第1秒的帧
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    } else {
                        imageView.setImageResource(android.R.drawable.ic_media_play);
                    }
                } finally {
                    retriever.release();
                }
            } else {
                imageView.setImageResource(android.R.drawable.ic_media_play);
            }
        } catch (Exception e) {
            Log.e(TAG, "加载视频缩略图失败: " + videoPath, e);
            imageView.setImageResource(android.R.drawable.ic_media_play);
        }
    }
    
    /**
     * 播放视频
     */
    private void playVideo(String videoPath) {
        try {
            File videoFile = new File(videoPath);
            if (videoFile.exists()) {
                Uri videoUri = mediaFileManager.getFileUri(videoFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(videoUri, "video/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "未找到视频播放器", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "视频文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "播放视频失败: " + videoPath, e);
            Toast.makeText(getContext(), "播放视频失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 格式化文件大小
     */
    private String formatFileSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format(Locale.getDefault(), "%.1f KB", bytes / 1024.0);
        } else {
            return String.format(Locale.getDefault(), "%.1f MB", bytes / (1024.0 * 1024.0));
        }
    }
    
    /**
     * 修复的createAttachmentViewFromSaved方法
     */
    private View createAttachmentViewFromSavedFixed(String path, String type) {
        try {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            View view = null;
            
            switch (type.toLowerCase()) {
                case "image":
                    view = inflater.inflate(R.layout.item_image_attachment, layoutAttachments, false);
                    ImageView imageView = view.findViewById(R.id.imageView);
                    loadImageFromPath(imageView, path);
                    break;
                    
                case "video":
                    view = inflater.inflate(R.layout.item_video_attachment, layoutAttachments, false);
                    ImageView videoThumbnail = view.findViewById(R.id.iv_video_thumbnail);
                    ImageView playButton = view.findViewById(R.id.iv_play_button);
                    TextView fileSizeText = view.findViewById(R.id.tv_file_size);
                    
                    // 加载视频缩略图
                    loadVideoThumbnail(videoThumbnail, path);
                    
                    // 设置文件大小
                    long fileSize = mediaFileManager.getFileSize(path);
                    fileSizeText.setText(formatFileSize(fileSize));
                    
                    // 设置播放按钮点击事件
                    playButton.setOnClickListener(v -> playVideo(path));
                    videoThumbnail.setOnClickListener(v -> playVideo(path));
                    break;
                    
                case "audio":
                    view = inflater.inflate(R.layout.item_audio_attachment, layoutAttachments, false);
                    TextView audioText = view.findViewById(R.id.tvAudioName);
                    audioText.setText("🎵 音频文件: " + getFileNameFromPath(path));
                    
                    // 添加播放音频功能
                    view.setOnClickListener(v -> playAudio(path));
                    break;
                    
                case "document":
                    view = inflater.inflate(R.layout.item_document_attachment, layoutAttachments, false);
                    TextView docText = view.findViewById(R.id.tvDocumentName);
                    docText.setText("📄 文档: " + getFileNameFromPath(path));
                    
                    // 添加打开文档功能
                    view.setOnClickListener(v -> openDocument(path));
                    break;
            }
            
            return view;
        } catch (Exception e) {
            Log.e(TAG, "创建附件视图失败", e);
            return null;
        }
    }
    
    /**
     * 播放音频
     */
    private void playAudio(String audioPath) {
        try {
            File audioFile = new File(audioPath);
            if (audioFile.exists()) {
                Uri audioUri = mediaFileManager.getFileUri(audioFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(audioUri, "audio/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "未找到音频播放器", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "音频文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "播放音频失败: " + audioPath, e);
            Toast.makeText(getContext(), "播放音频失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 打开文档
     */
    private void openDocument(String docPath) {
        try {
            File docFile = new File(docPath);
            if (docFile.exists()) {
                Uri docUri = mediaFileManager.getFileUri(docFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(docUri, "application/*");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(getContext(), "未找到文档查看器", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "文档文件不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "打开文档失败: " + docPath, e);
            Toast.makeText(getContext(), "打开文档失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadImageFromPath(ImageView imageView, String path) {
        try {
            if (path.startsWith("content://") || path.startsWith("file://")) {
                Uri uri = Uri.parse(path);
                imageView.setImageURI(uri);
            } else {
                // 处理本地文件路径
                java.io.File file = new java.io.File(path);
                if (file.exists()) {
                    Uri uri = Uri.fromFile(file);
                    imageView.setImageURI(uri);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "加载图片失败", e);
            // 设置默认图片，使用现有的图标
            imageView.setImageResource(android.R.drawable.ic_menu_gallery);
        }
    }
    
    private String getFileNameFromPath(String path) {
        if (path == null) return "未知文件";
        
        int lastSlash = path.lastIndexOf("/");
        if (lastSlash != -1 && lastSlash < path.length() - 1) {
            return path.substring(lastSlash + 1);
        }
        return path;
    }
    
    private void clearAttachments() {
        layoutAttachments.removeAllViews();
        attachmentPaths.clear();
        attachmentTypes.clear();
    }
    
    private void updateEditMode() {
        etTitle.setEnabled(isEditMode);
        etContent.setEnabled(isEditMode);
        
        if (isEditMode) {
            etTitle.setBackgroundResource(R.drawable.edit_text_background);
            etContent.setBackgroundResource(R.drawable.edit_text_background);
            etTitle.requestFocus();
        } else {
            etTitle.setBackgroundResource(android.R.color.transparent);
            etContent.setBackgroundResource(android.R.color.transparent);
        }
        
        // 更新菜单项显示
        updateMenuItems();
    }
    
    private void updateWordCount() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        int wordCount = title.length() + content.length();
        tvWordCount.setText(wordCount + " 字");
    }
    
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.diary_enhanced_menu, menu);
        editMenuItem = menu.findItem(R.id.action_edit);
        saveMenuItem = menu.findItem(R.id.action_save);
        attachMenuItem = menu.findItem(R.id.action_attach);
        updateMenuItems();
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    private void updateMenuItems() {
        if (editMenuItem != null && saveMenuItem != null && attachMenuItem != null) {
            editMenuItem.setVisible(!isEditMode);
            saveMenuItem.setVisible(isEditMode);
            attachMenuItem.setVisible(isEditMode);
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        
        if (itemId == R.id.action_edit) {
            startEditMode();
            return true;
        } else if (itemId == R.id.action_save) {
            saveDiary();
            return true;
        } else if (itemId == R.id.action_attach) {
            showAttachmentOptions();
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    private void startEditMode() {
        isEditMode = true;
        updateEditMode();
        Toast.makeText(getContext(), "进入编辑模式", Toast.LENGTH_SHORT).show();
    }
    
    private void showAttachmentOptions() {
        String[] options = {
            "拍照", "选择图片", "录制视频", "选择视频", 
            "选择音频", "选择文档 (PDF/DOCX)"
        };
        
        new AlertDialog.Builder(requireContext())
            .setTitle("添加附件")
            .setItems(options, (dialog, which) -> {
                switch (which) {
                    case 0: // 拍照
                        captureImage();
                        break;
                    case 1: // 选择图片
                        pickImage();
                        break;
                    case 2: // 录制视频
                        captureVideo();
                        break;
                    case 3: // 选择视频
                        pickVideo();
                        break;
                    case 4: // 选择音频
                        pickAudio();
                        break;
                    case 5: // 选择文档
                        pickDocument();
                        break;
                }
            })
            .show();
    }
    
    private void captureImage() {
        // 检查相机权限
        if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), 
                    new String[]{android.Manifest.permission.CAMERA}, 
                    PERMISSION_REQUEST_CAMERA);
            return;
        }
        
        try {
            // 创建图片文件
            File photoFile = mediaFileManager.createImageFile();
            if (photoFile != null) {
                currentPhotoPath = photoFile.getAbsolutePath();
                
                // 创建Intent并设置输出文件
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri photoURI = mediaFileManager.getFileUri(photoFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                
                // 授予临时权限
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                } else {
                    Toast.makeText(getContext(), "未找到相机应用", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "无法创建图片文件", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "启动相机失败", e);
            Toast.makeText(getContext(), "启动相机失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void pickImage() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_IMAGE_PICK);
        } else {
            // 尝试使用GET_CONTENT作为备选
            Intent fallbackIntent = new Intent(Intent.ACTION_GET_CONTENT);
            fallbackIntent.setType("image/*");
            if (fallbackIntent.resolveActivity(requireActivity().getPackageManager()) != null) {
                startActivityForResult(fallbackIntent, REQUEST_IMAGE_PICK);
            } else {
                Toast.makeText(getContext(), "未找到图片选择应用", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    private void captureVideo() {
        // 检查相机权限
        if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), 
                    new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO}, 
                    PERMISSION_REQUEST_CAMERA);
            return;
        }
        
        try {
            // 创建视频文件
            File videoFile = mediaFileManager.createVideoFile();
            if (videoFile != null) {
                currentVideoPath = videoFile.getAbsolutePath();
                
                // 创建Intent并设置输出文件
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                Uri videoURI = mediaFileManager.getFileUri(videoFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, videoURI);
                
                // 设置视频质量和时长限制
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 高质量
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60); // 60秒限制
                
                // 授予临时权限
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                    startActivityForResult(intent, REQUEST_VIDEO_CAPTURE);
                } else {
                    Toast.makeText(getContext(), "未找到录像应用", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "无法创建视频文件", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "启动录像失败", e);
            Toast.makeText(getContext(), "启动录像失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void pickVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("video/*");
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_VIDEO_PICK);
        } else {
            // 尝试使用GET_CONTENT作为备选
            Intent fallbackIntent = new Intent(Intent.ACTION_GET_CONTENT);
            fallbackIntent.setType("video/*");
            if (fallbackIntent.resolveActivity(requireActivity().getPackageManager()) != null) {
                startActivityForResult(fallbackIntent, REQUEST_VIDEO_PICK);
            } else {
                Toast.makeText(getContext(), "未找到视频选择应用", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    private void pickAudio() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_AUDIO_PICK);
        } else {
            Toast.makeText(getContext(), "未找到音频选择应用", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void pickDocument() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        String[] mimeTypes = {"application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        
        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_DOCUMENT_PICK);
        } else {
            Toast.makeText(getContext(), "未找到文档选择应用", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        switch (requestCode) {
            case PERMISSION_REQUEST_CAMERA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限获得，重新尝试操作
                    showAttachmentOptions();
                } else {
                    Toast.makeText(getContext(), "需要相机权限才能拍照/录像", Toast.LENGTH_SHORT).show();
                }
                break;
                
            case PERMISSION_REQUEST_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限获得，重新尝试操作
                    showAttachmentOptions();
                } else {
                    Toast.makeText(getContext(), "需要存储权限才能访问文件", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode != getActivity().RESULT_OK) {
            Log.d(TAG, "Activity result not OK: " + resultCode);
            return;
        }
        
        try {
            switch (requestCode) {
                case REQUEST_IMAGE_CAPTURE:
                    handleImageCapture();
                    break;
                    
                case REQUEST_IMAGE_PICK:
                    if (data != null && data.getData() != null) {
                        handleImagePick(data.getData());
                    }
                    break;
                    
                case REQUEST_VIDEO_CAPTURE:
                    handleVideoCapture();
                    break;
                    
                case REQUEST_VIDEO_PICK:
                    if (data != null && data.getData() != null) {
                        handleVideoPick(data.getData());
                    }
                    break;
                    
                case REQUEST_AUDIO_PICK:
                    if (data != null && data.getData() != null) {
                        handleAudioPick(data.getData());
                    }
                    break;
                    
                case REQUEST_DOCUMENT_PICK:
                    if (data != null && data.getData() != null) {
                        handleDocumentPick(data.getData());
                    }
                    break;
            }
        } catch (Exception e) {
            Log.e(TAG, "处理Activity结果失败", e);
            Toast.makeText(getContext(), "处理文件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleImageCapture() {
        if (currentPhotoPath != null && mediaFileManager.fileExists(currentPhotoPath)) {
            addAttachmentFromFile(currentPhotoPath, "image");
            currentPhotoPath = null;
        } else {
            Toast.makeText(getContext(), "拍照失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleImagePick(Uri imageUri) {
        File copiedFile = mediaFileManager.copyFileToAppDirectory(imageUri, "image");
        if (copiedFile != null) {
            addAttachmentFromFile(copiedFile.getAbsolutePath(), "image");
        } else {
            Toast.makeText(getContext(), "保存图片失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleVideoCapture() {
        if (currentVideoPath != null && mediaFileManager.fileExists(currentVideoPath)) {
            addAttachmentFromFile(currentVideoPath, "video");
            currentVideoPath = null;
        } else {
            Toast.makeText(getContext(), "录像失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleVideoPick(Uri videoUri) {
        File copiedFile = mediaFileManager.copyFileToAppDirectory(videoUri, "video");
        if (copiedFile != null) {
            addAttachmentFromFile(copiedFile.getAbsolutePath(), "video");
        } else {
            Toast.makeText(getContext(), "保存视频失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleAudioPick(Uri audioUri) {
        File copiedFile = mediaFileManager.copyFileToAppDirectory(audioUri, "audio");
        if (copiedFile != null) {
            addAttachmentFromFile(copiedFile.getAbsolutePath(), "audio");
        } else {
            Toast.makeText(getContext(), "保存音频失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void handleDocumentPick(Uri documentUri) {
        File copiedFile = mediaFileManager.copyFileToAppDirectory(documentUri, "document");
        if (copiedFile != null) {
            addAttachmentFromFile(copiedFile.getAbsolutePath(), "document");
        } else {
            Toast.makeText(getContext(), "保存文档失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void addAttachmentFromFile(String filePath, String fileType) {
        try {
            // 添加到附件列表
            attachmentPaths.add(filePath);
            attachmentTypes.add(fileType);
            
            // 创建并添加视图
            View attachmentView = createAttachmentViewFromSavedFixed(filePath, fileType);
            if (attachmentView != null) {
                layoutAttachments.addView(attachmentView);
                
                // 添加删除按钮
                addDeleteButtonToAttachment(attachmentView, attachmentPaths.size() - 1);
            }
            
            // 如果当前有日记，立即保存附件信息
            if (currentDiary != null) {
                currentDiary.addAttachment(filePath, fileType);
                diaryViewModel.updateDiaryEntry(currentDiary);
            }
            
            Toast.makeText(getContext(), fileType + "附件添加成功", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "添加附件: " + filePath + ", 类型: " + fileType);
            
        } catch (Exception e) {
            Log.e(TAG, "添加附件失败", e);
            Toast.makeText(getContext(), "添加附件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void addDeleteButtonToAttachment(View attachmentView, int attachmentIndex) {
        // 在附件视图上添加删除按钮
        attachmentView.setOnLongClickListener(v -> {
            new AlertDialog.Builder(requireContext())
                .setTitle("删除附件")
                .setMessage("确定要删除这个附件吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    removeAttachment(attachmentIndex);
                })
                .setNegativeButton("取消", null)
                .show();
            return true;
        });
    }
    
    private void removeAttachment(int index) {
        try {
            if (index >= 0 && index < attachmentPaths.size()) {
                String filePath = attachmentPaths.get(index);
                
                // 删除文件
                mediaFileManager.deleteFile(filePath);
                
                // 从列表中移除
                attachmentPaths.remove(index);
                attachmentTypes.remove(index);
                
                // 重新加载附件显示
                clearAttachments();
                if (currentDiary != null) {
                    loadAttachments(currentDiary);
                }
                
                // 更新日记
                if (currentDiary != null) {
                    currentDiary.setAttachmentPaths(new ArrayList<>(attachmentPaths));
                    currentDiary.setAttachmentTypes(new ArrayList<>(attachmentTypes));
                    diaryViewModel.updateDiaryEntry(currentDiary);
                }
                
                Toast.makeText(getContext(), "附件已删除", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "删除附件失败", e);
            Toast.makeText(getContext(), "删除附件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void saveDiary() {
        String title = etTitle.getText().toString().trim();
        String content = etContent.getText().toString().trim();
        
        if (title.isEmpty() && content.isEmpty() && attachmentPaths.isEmpty()) {
            Toast.makeText(getContext(), "请输入标题、内容或添加附件", Toast.LENGTH_SHORT).show();
            return;
        }
        
        try {
            if (currentDiary == null) {
                // 创建新日记
                currentDiary = new DiaryEntry();
                currentDiary.setUserId(UserManager.getInstance().getCurrentUser().getId());
                currentDiary.setDate(currentDate);
                currentDiary.setCreatedDate(new Date());
            }
            
            currentDiary.setTitle(title);
            currentDiary.setContent(content);
            currentDiary.setUpdatedDate(new Date());
            
            // 保存附件信息
            if (!attachmentPaths.isEmpty()) {
                currentDiary.setAttachmentPaths(new ArrayList<>(attachmentPaths));
                currentDiary.setAttachmentTypes(new ArrayList<>(attachmentTypes));
                
                Log.d(TAG, "保存附件数量: " + attachmentPaths.size());
            }
            
            // 异步保存到数据库
            new Thread(() -> {
                try {
                    if (currentDiary.getId() == 0) {
                        diaryViewModel.insertDiaryEntry(currentDiary);
                        Log.d(TAG, "新日记已插入数据库");
                    } else {
                        diaryViewModel.updateDiaryEntry(currentDiary);
                        Log.d(TAG, "日记已更新到数据库");
                    }
                    
                    // 在主线程显示成功消息
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            isEditMode = false;
                            updateEditMode();
                            Toast.makeText(getContext(), "日记保存成功", Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    Log.e(TAG, "保存日记失败", e);
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            }).start();
            
        } catch (Exception e) {
            Log.e(TAG, "保存日记失败", e);
            Toast.makeText(getContext(), "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onDateChanged(Date newDate) {
        currentDate = newDate;
        updateDateDisplay();
        loadCurrentDiary();
        loadCompletedTasks();
    }
    
    public boolean onBackPressed() {
        if (isEditMode) {
            showExitEditDialog();
            return true;
        }
        return false;
    }
    
    private void showExitEditDialog() {
        new AlertDialog.Builder(requireContext())
            .setTitle("退出编辑")
            .setMessage("是否保存当前编辑的内容？")
            .setPositiveButton("保存", (dialog, which) -> saveDiary())
            .setNegativeButton("不保存", (dialog, which) -> {
                isEditMode = false;
                updateEditMode();
                updateUI(); // 重新加载原始内容
            })
            .setNeutralButton("取消", null)
            .show();
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dateManager != null) {
            dateManager.removeDateChangeListener(this);
        }
    }
    
    /**
     * 完成任务适配器
     */
    private static class CompletedTasksAdapter extends RecyclerView.Adapter<CompletedTasksAdapter.ViewHolder> {
        private List<Task> tasks = new ArrayList<>();
        
        public void setTasks(List<Task> tasks) {
            this.tasks = tasks;
            notifyDataSetChanged();
        }
        
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_completed_task, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Task task = tasks.get(position);
            holder.tvTaskTitle.setText(task.getTitle());
            holder.tvTaskType.setText(task.getType());
            if (task.getCompletedDate() != null) {
                SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
                holder.tvCompletedTime.setText("完成时间: " + timeFormat.format(task.getCompletedDate()));
            }
        }
        
        @Override
        public int getItemCount() {
            return tasks.size();
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvTaskTitle, tvTaskType, tvCompletedTime;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvTaskTitle = itemView.findViewById(R.id.tv_task_title);
                tvTaskType = itemView.findViewById(R.id.tv_task_type);
                tvCompletedTime = itemView.findViewById(R.id.tv_completed_time);
            }
        }
    }
}

